/*
 *  Copyright 2016 http://www.kedacomframework.org
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */

package com.kedacom.ctsp.authz.oauth2.service.client;

import com.kedacom.ctsp.authz.oauth2.OAuth2ServerProperties;
import com.kedacom.ctsp.authz.oauth2.core.GrantType;
import com.kedacom.ctsp.authz.oauth2.entity.AccessToken;
import com.kedacom.ctsp.authz.oauth2.entity.Client;
import com.kedacom.ctsp.authz.oauth2.service.AbstractAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;

import static com.kedacom.ctsp.authz.oauth2.core.ErrorType.ILLEGAL_CLIENT_ID;
import static com.kedacom.ctsp.authz.oauth2.core.ErrorType.ILLEGAL_CLIENT_SECRET;

/**
 * TODO 完成注释
 *
 * @author
 */
public class DefaultClientCredentialGranter extends AbstractAuthorizationService implements ClientCredentialGranter {

    @Autowired
    private OAuth2ServerProperties serverProperties;

    @Override
    public AccessToken requestToken(ClientCredentialRequest request) {
        String clientId = request.getClientId();
        String clientSecret = request.getClientSecret();

        assertParameterNotBlank(clientId, ILLEGAL_CLIENT_ID);
        assertParameterNotBlank(clientSecret, ILLEGAL_CLIENT_SECRET);

        Client client = getClient(clientId, clientSecret);
        assertGrantTypeSupport(client, GrantType.CLIENT_CREDENTIALS);

        AccessToken accessToken = accessTokenService.createToken();
        // 设置自定义的属性,其他属性在create的时候已经被设置
        accessToken.setOwnerId(client.getOwnerId());
        accessToken.setExpiresIn(serverProperties.getAccessTokenExpireSeconds());
        accessToken.setScope(client.getSupportGrantScope());
        accessToken.setClientId(client.getSign());
        accessToken.setGrantType(GrantType.CLIENT_CREDENTIALS);

        //保存token
        return accessTokenService.saveOrUpdateToken(accessToken);
    }
}
